package com.yuncheng.oaApi.controller;

import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.yuncheng.oaApi.utils.GetUuIdUtils;;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.oaApi.config.OaMinioUtils;
import com.yuncheng.oaApi.constant.OaCommonFlowConstant;
import com.yuncheng.oaApi.constant.OaLogConstant;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.oaApi.utils.*;
import com.yuncheng.oaApi.vo.HttpResultVo;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.utils.I18nUtil;
import com.yuncheng.utils.ThreadContextHelper;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.annotation.AutoLog;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.oaApi.entity.OaFjzykEntity;
import com.yuncheng.oaApi.service.IOaFjzykEntityService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.oaApi.weboffice.OaWebOfficeFile;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import utils.DateConversionUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

/**
 * @Description: OA附件资源库
 * @Author: lhb
 * @Date: 2023-08-11
 * @Version: V1.0
 */
@Api(tags = "OA附件资源库接口")
@RestController
@RequestMapping("/api/spzx-oa/oaFjzyk")
public class OaFjzykController extends BaseController<OaFjzykEntity, IOaFjzykEntityService> {

    private static final Logger log = LoggerFactory.getLogger(OaFjzykController.class);

    @Resource
    private IOaFjzykEntityService oaFjzykService;

    @Resource
    @Lazy
    private ISpcyLogService spcyLogService;

    @Resource
    @Lazy
    private OaLocalFileUploadUtils oaLocalFileUploadUtils;

    @Resource
    private OaWebOfficeFile oaWebOfficeFIle;

    @Resource
    private OaMinioUtils oaMinioUtils;

    /**
     * 分页列表查询
     *
     * @param oaFjzykEntity
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "OA附件资源库-分页列表查询")
    @ApiOperation(value = "OA附件资源库-分页列表查询")
    @GetMapping(value = "/list")
    public HttpResult<?> queryPageList(OaFjzykEntity oaFjzykEntity,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        String foaid = oaFjzykEntity.getFoaid();
        int size = foaid.split(",").length;

        if (size == 1) {
            LambdaQueryWrapper<OaFjzykEntity> queryWrapper = new LambdaQueryWrapper<>();
//        QueryWrapper<OaFjzyk> queryWrapper = QueryBuilder.initQueryWrapper(oaFjzyk, req.getParameterMap());
            Page<OaFjzykEntity> page = new Page<>(pageNo, pageSize);
            queryWrapper.eq(StringUtils.isNotBlank(oaFjzykEntity.getFoaid()), OaFjzykEntity::getFoaid, oaFjzykEntity.getFoaid());
            queryWrapper.eq(StringUtils.isNotBlank(oaFjzykEntity.getFlx()), OaFjzykEntity::getFlx, oaFjzykEntity.getFlx());
            queryWrapper.eq(StringUtils.isNotBlank(oaFjzykEntity.getFmc()), OaFjzykEntity::getFmc, oaFjzykEntity.getFmc());
            queryWrapper.orderByDesc(OaFjzykEntity::getFscsj);
            IPage<OaFjzykEntity> pageList = oaFjzykService.page(page, queryWrapper);

            return HttpResultVo.HttpResultSave(pageList);
        }else {

            List<String> foaidList = Arrays.asList(foaid.split(","));
            List<OaFjzykEntity> resultList = new ArrayList<>();

            for (String id : foaidList) {
                List<OaFjzykEntity> oaFjzyks = oaFjzykService.list(new LambdaQueryWrapper<OaFjzykEntity>()
                        .eq(OaFjzykEntity::getFoaid, id));

                resultList.addAll(oaFjzyks);
            }

            return HttpResultVo.HttpResultList(resultList);
        }
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "OA附件资源库-通过id删除")
    @ApiOperation(value = "OA附件资源库-通过id删除")
    @DeleteMapping(value = "/delete")
    public HttpResult<?> delete(@RequestParam("id") String id) {
        oaFjzykService.removeById(id);
        return HttpResult.ok(I18nUtil.message("delete.success"));
    }

    /**
     * 通过id批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "OA附件资源库-批量删除")
    @ApiOperation(value = "OA附件资源库-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public HttpResult<?> deleteBatch(@RequestParam("ids") String ids) {
        oaFjzykService.removeByIds(Arrays.asList(ids.split(",")));
        return HttpResult.ok(I18nUtil.message("delete.success"));
    }

//    /**
//     * 通过id查询
//     *
//     * @param id
//     * @return
//     */
//    @AutoLog(value = "OA附件资源库-通过id查询")
//    @ApiOperation(value = "OA附件资源库-通过id查询")
//    @GetMapping(value = "/queryById")
//    public HttpResult<?> queryById(@RequestParam("id") String id) {
//        OaFjzyk oaFjzyk = oaFjzykService.getById(id);
//        return HttpResult.ok(oaFjzyk);
//    }


//    /**
//     * 编辑
//     *
//     * @param oaFjzyk
//     * @return
//     */
//    @AutoLog(value = "OA附件资源库-编辑")
//    @ApiOperation(value = "OA附件资源库-编辑")
//    @PutMapping(value = "/edit")
//    public HttpResult<?> edit(@RequestBody OaFjzyk oaFjzyk) {
//        oaFjzykService.updateById(oaFjzyk);
//        return HttpResult.ok(I18nUtil.message("update.success"));
//    }


    /**
     * @Author: lhb
     * @Description : 如果在第一次上传附件没有oaid 传空字符串，并在保存或者提交后 再次调取编辑接口更新oaid
     * @DateTime:
     * @Params:
     */
    @AutoLog(value = "OA附件-上传文件")
    @ApiOperation(value = "OA附件-上传文件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file", value = "文件不能为空", required = true)
    })
    @PostMapping(value = "/uploadOAfj")
    public HttpResult<?> uploadOAfj(@RequestPart("file") MultipartFile file,
                                    @RequestParam(value = "oaid", defaultValue = "") String oaid,
                                    @RequestParam(value = "flcmc", defaultValue = "") String flcmc) {


        OaFjzykEntity oafj = new OaFjzykEntity();

        if (StringUtils.isBlank(oaid)) {
            return HttpResult.error("没有绑定流程id");
        }
        if (StringUtils.isBlank(flcmc)) {
            return HttpResult.error("没有绑定流程名称");
        }


        String originalFilename = file.getOriginalFilename();
        // 文件类型
        String wjlx = originalFilename.substring(originalFilename.lastIndexOf("."));
        //文件名称
        String fileName = file.getOriginalFilename();
        int startIndex = fileName.replaceAll("\\\\", "/").lastIndexOf("/");
        fileName = fileName.substring(startIndex + 1).substring(0, fileName.indexOf("."));


        String wjccmc = fileName + wjlx; //文件存储名称
        String newDir = OaCommonFlowConstant.OA_FILE_FJ; //文件夹名称


        oaLocalFileUploadUtils.uploadZdyFile(file, wjccmc, newDir); // 上传文件

        String cflj = "/" + newDir + "/" + wjccmc;
        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
        oafj.setId(GetUuIdUtils.ReplaceUuId());
        oafj.setFmc(fileName);
        oafj.setFwjlx(wjlx);
        oafj.setFwjmc(wjccmc);
        oafj.setFwjlj(cflj);
        oafj.setFscr(currentUser.getName());
        oafj.setFscrid(currentUser.getId());
        oafj.setFscsj(DateConversionUtils.DateToYMDHMSChineseString(new Date()));
        oafj.setFoaid(oaid);
        oafj.setFlcmc(flcmc);
        oaFjzykService.save(oafj);
        String id = oafj.getId();
        if (StringUtils.isNotBlank(id)) {
            String czContent = "上传附件文档:";
            Map<String, Object> wjjlMap = ObjectToMapUtils.objectToMap(oafj);
            czContent += LogUtils.MapToStringMethod(wjjlMap);
            spcyLogService.addLogs(OaLogConstant.LOGS_OA_FJ, czContent, id, OaCommonFlowConstant.LOGS_SYS_TYPE_BC, OaCommonFlowConstant.LOGS_SYS_TYPE_BC);
            oaFjzykService.zltxwjToPdf(oafj); // 生成pdf版文件

        }
        return HttpResult.ok("上传成功");


    }


    @AutoLog(value = "OA-下载附件")
    @ApiOperation(value = "OA-下载附件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "附件id", required = true)
    })
    @GetMapping(value = "/getOaFile")
    public void getOaFile(@RequestParam("id") String fileId, HttpServletResponse response) {
        if (StringUtils.isEmpty(fileId)) {
            log.error("OA附件id为空");
            return;
        }
        OaFjzykEntity oaFjzykEntity = oaFjzykService.getById(fileId);
        if (oaFjzykEntity == null) {
            throw new BusinessException("OA附件文件id为-{}的文件记录不存在" + fileId);
        }
        oaLocalFileUploadUtils.ejzLocalFileURlByZdy(oaFjzykEntity.getFwjlj(), response);
    }

    @AutoLog(value = "OA附件-下载pdf版文件")
    @ApiOperation(value = "OA附件-下载pdf版文件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "oa文件id", required = true)
    })
    @GetMapping(value = "/getOaPdfFile")
    public void getOaPdfFile(@RequestParam("id") String fileId, HttpServletResponse response) {
        if (StringUtils.isEmpty(fileId)) {
            log.error("OA附件文件id为空");
            return;
        }
        OaFjzykEntity oaFjzykEntity = oaFjzykService.getById(fileId);
        if (oaFjzykEntity == null) {
            log.error("OA附件文件id为-{}的文件记录不存在", fileId);
            throw new BusinessException("OA附件文件id为-{}的文件记录不存在" + fileId);
        }
        if (StringUtils.isBlank(oaFjzykEntity.getFpdfwjlj())) {
            if (StringUtils.isNotBlank(oaFjzykEntity.getFwjlj())) {
                oaFjzykService.zltxwjToPdf(oaFjzykEntity);
                OaFjzykEntity oaFjzykEntity2 = oaFjzykService.getById(fileId);
                oaLocalFileUploadUtils.ejzLocalFileURlByZdy(oaFjzykEntity2.getFpdfwjlj(), response);
            } else {
                throw new BusinessException("OA附件文件id为-{}的文件不存在" + fileId);
            }
        } else {
            oaLocalFileUploadUtils.ejzLocalFileURlByZdy(oaFjzykEntity.getFpdfwjlj(), response);
        }
    }

    @AutoLog(value = "OA-打开文档 -服务端-只读")
    @ApiOperation(value = "OA-打开文档-服务端-只读")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "附件id", required = true)
    })
    @GetMapping(value = "/openFile")
    public HttpResult<?> openFile(@RequestParam("id") String id) {
        OaFjzykEntity wjid = oaFjzykService.getById(id);
        if (wjid == null) {
            return HttpResult.error("文件不存在");
        }
        if (StringUtils.isNotBlank(wjid.getFwjlx()) && wjid.getFwjlx().equals(".pdf")) {
            return HttpResult.error("当前文档为pdf文档，请选择重新编辑文档");
        }
//        String url = oaWebOfficeFIle.openFileByOafj(wjid, wjid.getId(), wjid.getFwjlj(), 1);
        String url = oaWebOfficeFIle.openFileByOafjbj(wjid, wjid.getId(), wjid.getFwjlj(), 1);

        Map resultMap = new HashMap();

        resultMap.put("wordUrl", url);
        return HttpResult.ok(resultMap);

    }


    /********************************minio，上传附件，预览，下载****************************************************************************************************************************************/

    /**
     * @param: file 文件，oaid 文件绑定的主题id
     * @Description: minio 上传文件
     * @auther: lhb
     * @date: 2023/8/21 10:10
     */
//    @AutoLog(value = "minio-OA-上传附件")
    @ApiOperation(value = "minio-OA-上传附件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file", value = "文件不能为空", required = true)
    })

    @PostMapping(value = "/fjupload")
    public HttpResult fjupload(@RequestPart("file") MultipartFile file, @RequestParam(value = "oaid", defaultValue = "") String oaid) {
        OaFjzykEntity oaFjzykEntity = new OaFjzykEntity();

        String id = "";
        if (file == null) {
            return HttpResult.error("上传失败,请先选择文件");
        }

        if (StringUtils.isBlank(oaid)) {
            return HttpResult.error("没有绑定流程id");
        }
        String originalFilename = file.getOriginalFilename();
        // 文件类型
        String wjlx = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 文件名
        String sjmc = GetUuIdUtils.generateUuid();

        String wjccmc = sjmc + wjlx;

        String nowDay = DateConversionUtils.DateToMonth(new Date()); // 获取当前日期 yyyy-MM-dd

        //如果不放置文件， 在使用minio上传自定义文件夹时，文件要上传 ，在上传时 会直接上传 日期作为文件
        //附件存放地址-带文件
        String newDirs = OaCommonFlowConstant.OA_FILE_FJ + "/" + nowDay + "/" + wjccmc;

        String fileName = file.getOriginalFilename(); //带后缀的真实名称
        //上传文件
        oaMinioUtils.uploadFile(file, newDirs);

        //个人信息
        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
        id = GetUuIdUtils.ReplaceUuId();
        oaFjzykEntity.setFmc(fileName); //文件真实名称
        oaFjzykEntity.setFwjmc(wjccmc); //虚假名称
        oaFjzykEntity.setId(id);
        oaFjzykEntity.setFwjlx(wjlx);
        oaFjzykEntity.setFwjlj(newDirs);
        oaFjzykEntity.setFscr(currentUser.getName());
        oaFjzykEntity.setFscrid(currentUser.getId());
        oaFjzykEntity.setFscsj(DateConversionUtils.DateToYMDHMSChineseString(new Date()));
        oaFjzykEntity.setFoaid(oaid);
        oaFjzykService.save(oaFjzykEntity);
        if (StringUtils.isNotBlank(id)) {
            String czContent = "上传附件文档:";
            Map<String, Object> wjjlMap = ObjectToMapUtils.objectToMap(oaFjzykEntity);
            czContent += LogUtils.MapToStringMethod(wjjlMap);
            spcyLogService.addLogs(OaLogConstant.LOGS_OA_FJ, czContent, id, OaCommonFlowConstant.LOGS_SYS_TYPE_BC, OaCommonFlowConstant.LOGS_SYS_TYPE_BC);

        }
        return HttpResult.ok("上传成功");
    }


//    @AutoLog(value = "申请附件模板-上传附件")
    @ApiOperation(value = "申请附件模板-上传附件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file", value = "文件不能为空", required = true)
    })

    @PostMapping(value = "/sqfjmbupload")
    public HttpResult sqfjmbupload(MultipartFile file) {
        OaFjzykEntity oaFjzykEntity = new OaFjzykEntity();

        String id = "";
        if (file == null) {
            return HttpResult.error("上传失败,请先选择文件");
        }


        String originalFilename = file.getOriginalFilename();
        // 文件类型
        String wjlx = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 文件名
        String sjmc = GetUuIdUtils.generateUuid();

        String wjccmc = sjmc + wjlx;

        String nowDay = DateConversionUtils.DateToMonth(new Date()); // 获取当前日期 yyyy-MM-dd

        //如果不放置文件， 在使用minio上传自定义文件夹时，文件要上传 ，在上传时 会直接上传 日期作为文件
        //附件存放地址-带文件
        String newDirs = OaCommonFlowConstant.OA_FILE_FJ + "/" + nowDay + "/" + wjccmc;

        String fileName = file.getOriginalFilename(); //带后缀的真实名称
        //上传文件
        oaMinioUtils.uploadFile(file, newDirs);

        //个人信息
        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
        id = GetUuIdUtils.ReplaceUuId();
        oaFjzykEntity.setFmc(fileName); //文件真实名称
        oaFjzykEntity.setFwjmc(wjccmc); //虚假名称
        oaFjzykEntity.setId(id);
        oaFjzykEntity.setFwjlx(wjlx);
        oaFjzykEntity.setFwjlj(newDirs);
        oaFjzykEntity.setFscr(currentUser.getName());
        oaFjzykEntity.setFscrid(currentUser.getId());
        oaFjzykEntity.setFscsj(DateConversionUtils.DateToYMDHMSChineseString(new Date()));
        oaFjzykEntity.setFlx(OaCommonFlowConstant.XZSWSP_SQFJMB);
        oaFjzykService.save(oaFjzykEntity);
        if (StringUtils.isNotBlank(id)) {
            String czContent = "上传附件文档:";
            Map<String, Object> wjjlMap = ObjectToMapUtils.objectToMap(oaFjzykEntity);
            czContent += LogUtils.MapToStringMethod(wjjlMap);
            spcyLogService.addLogs(OaLogConstant.LOGS_OA_FJ, czContent, id, OaCommonFlowConstant.LOGS_SYS_TYPE_BC, OaCommonFlowConstant.LOGS_SYS_TYPE_BC);

        }
        return HttpResult.ok("上传成功");
    }

//    @AutoLog(value = "minio-预览附件")
    @ApiOperation(value = "minio-预览附件")
    @ApiImplicitParam(name = "id", value = "附件id", required = true)
    @GetMapping(value = "Previewfj")
    public HttpResult Previewfj(String id) {
        Map resultMap = new HashMap();
        String url = ""; // 查询文件全路径
        OaFjzykEntity fjList = oaFjzykService.getById(id);
        String fwjlj = fjList.getFwjlj();

        url = oaMinioUtils.preview(fwjlj);
        resultMap.put("url", url);
        return HttpResult.ok(resultMap);
    }

//    @AutoLog(value = "minio-预览下载附件")
    @ApiOperation(value = "minio-预览下载附件")
    @ApiImplicitParam(name = "id", value = "附件id", required = true)
    @GetMapping(value = "downLoadOa")
    public void downLoadOa(String id, HttpServletResponse response) {
        OaFjzykEntity fjList = oaFjzykService.getById(id);
        String fwjlj = fjList.getFwjlj();
        if (StringUtils.isBlank(fwjlj)) {
            throw new BusinessException("当前附件记录不存在！");
        }
        oaMinioUtils.download(fwjlj, response);
    }

//    @AutoLog(value = "minio-删除路径和minio文件")
    @ApiOperation(value = "minio-删除路径和minio文件")
    @ApiImplicitParam(name = "id", value = "附件id", required = true)
    @GetMapping(value = "deleleMinioFile")
    public HttpResult deleleMinioFile(String id) {
        if (StringUtils.isBlank(id)) {
            return HttpResult.error("文件参数不能为空");
        }
        OaFjzykEntity fj = oaFjzykService.getById(id);

        if (fj == null) {
            return HttpResult.error("当前文件不存在，请刷新重试！");
        }

        oaFjzykService.removeById(id);

        oaMinioUtils.remove(fj.getFwjlj());

        return HttpResult.ok("删除成功");

    }

    /**
     * 数据转换
     *
     * @param oaFjzykEntity
     */
    private void formatValue(OaFjzykEntity oaFjzykEntity) {
    }
}
